/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package model;

import java.beans.Statement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author mosta
 */
public class CategoryDataBase {
    
    private Connection conn;
    private Statement stmt;
    private ResultSet result;
    private PreparedStatement prepStmt;

    public CategoryDataBase() {

            DatabaseConnection connection = new DatabaseConnection();
            conn = connection.startConnection();
    }

    public int fillCategory(CategoryBean category)
    {
        int value=0;
        String chkSql="select cat_name from category where cat_name=? ";
        String sql="insert into category"
                +"(cat_name)"
                +"VALUES (?)";
        try {
            prepStmt = conn.prepareStatement(chkSql);
            prepStmt.setString(1,category.getCatName());
            result = prepStmt.executeQuery();
            if(result.next())
            {
                return value;
            }
            else
            {
                prepStmt = conn.prepareStatement(sql);
//                prepStmt.setInt(1, category.getCatId());
                prepStmt.setString(1, category.getCatName());
                value = prepStmt.executeUpdate();
            }
        } catch (SQLException ex) {
            Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
        }

        return value;
    }
    public ArrayList<CategoryBean> getCategories(){
        ArrayList<CategoryBean> category=new ArrayList<CategoryBean>();
        
        String sql="select * from category";
        try {
            prepStmt=conn.prepareStatement(sql);
            result=prepStmt.executeQuery();
            while(result.next()){
               CategoryBean cBean=new CategoryBean();
                cBean.setCatId(result.getInt("cat_id"));
                cBean.setCatName(result.getString("cat_name"));
                category.add(cBean);
            }
        } catch (SQLException ex) {
            Logger.getLogger(CategoryDataBase.class.getName()).log(Level.SEVERE, null, ex);
        }
        return category;
    }
}
